import { View, Text } from '@tarojs/components';
import { Radio, Button, Form, InputNumber, Input } from '@nutui/nutui-react-taro';
import Taro, { useDidShow } from '@tarojs/taro';
import { useEffect, useState } from 'react';
import PageLayer from 'src/components/PageLayer/PageLayer';
import styles from './issueCoupon.module.less';
import issueCouponStore from './issueCouponStore';
import { observer } from "mobx-react-lite";
import issueCouponApi from './issueCouponApi';

// 发券页面
const IssueCoupon = observer(() => {
    // 表单状态
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [form] = Form.useForm();

    useDidShow(() => {
        // 页面显示时获取所有可用的券类型列表
        if (issueCouponStore.couponTypes.length === 0) {
            issueCouponStore.getCouponTypes().then(() => {
                // 确保默认选中第一个类型
                if (issueCouponStore.couponTypes.length > 0) {
                    form.setFieldValue('couponTypeId', issueCouponStore.couponTypes[0].couponTypeId);
                }
            });
        } else {
            // 如果已经有券类型，确保默认选中第一个
            if (issueCouponStore.couponTypes.length > 0) {
                form.setFieldValue('couponTypeId', issueCouponStore.couponTypes[0].couponTypeId);
            }
        }
    });

    // 重置表单
    const resetForm = () => {
        form.resetFields();
        // 重置时也默认选中第一个类型
        if (issueCouponStore.couponTypes.length > 0) {
            form.setFieldValue('couponTypeId', issueCouponStore.couponTypes[0].couponTypeId);
        }
        form.setFieldValue('couponCount', 10);
    };

    // 表单验证成功后执行的函数
    const onFinish = (values: any) => {
        const { targetUserId, couponTypeId, couponCount } = values;

        //分别校验3个参数必须都不为空
        if (!targetUserId) {
            Taro.showToast({ title: '请输入用户ID', icon: 'none' });
            return;
        }
        if (!couponTypeId) {
            Taro.showToast({ title: '请选择券类型', icon: 'none' });
            return;
        }
        if (!couponCount) {
            Taro.showToast({ title: '请输入发券数量', icon: 'none' });
            return;
        }

        // 二次确认提示
        Taro.showModal({
            title: '确认发券',
            content: `确定要向用户ID: ${targetUserId} 发放${couponCount}张券吗？`,
            success: async (res) => {
                if (res.confirm) {
                    setIsSubmitting(true);
                    try {
                        // 这里调用发券API，实际项目中替换为真实接口调用
                        console.log('发券信息:', { targetUserId, couponTypeId, couponCount });

                        // 调用实际的API接口
                        const result = await issueCouponApi.issueCoupon({
                            targetUserId,
                            couponTypeId,
                            couponCount
                        });

                        if (result.code === 200) {
                            Taro.showToast({ title: '发券成功', icon: 'success' });
                            // 重置表单
                            resetForm();
                        } else {
                            Taro.showToast({ title: result.message || '发券失败', icon: 'none' });
                        }
                    } catch (error) {
                        console.error('发券失败:', error);
                        Taro.showToast({ title: '发券失败，请重试', icon: 'none' });
                    } finally {
                        setIsSubmitting(false);
                    }
                }
            }
        });
    };

    return (
        <PageLayer
            title='发券'
            showBack
            className={styles.issueCoupon}
            hasTabBar={false} // 发券页面不显示tabBar
        >
            <Form
                form={form}
                labelPosition="right"
                initialValues={{
                    couponCount: 10,
                }}
                onFinish={onFinish}
                onFinishFailed={(values, errors) => {
                    Taro.showToast({ title: '请填写完整信息', icon: 'none' });
                }}
                footer={
                    <>
                        <Button
                            nativeType="submit"
                            block
                            type="primary"
                            className={styles.submitButton}
                            loading={isSubmitting}
                            disabled={isSubmitting}
                        >
                            确认发券
                        </Button>
                    </>
                }
            >
                <Form.Item
                    align="center"
                    label="用户ID"
                    name="targetUserId"
                    rules={[
                    ]}
                >
                    <Input
                        placeholder='请输入用户ID'
                        type='number'
                        className={styles.formInput}
                    />
                </Form.Item>

                <Form.Item
                    label="券码类型"
                    name="couponTypeId"
                    rules={[
                    ]}
                >
                    <Radio.Group
                        shape="button"
                        direction="horizontal"
                        style={{ marginTop: "-6rpx" }}
                    >
                        {issueCouponStore.couponTypes.map((type) => (
                            <Radio key={type.couponTypeId} value={type.couponTypeId}>
                                {type.typeName || `类型${type.couponTypeId}`}
                            </Radio>
                        ))}
                    </Radio.Group>
                </Form.Item>

                <Form.Item
                    label="发券数量"
                    name="couponCount"
                    rules={[
                    ]}
                >
                    <Input
                        type="number"
                        placeholder='请输入发券数量'
                    />
                </Form.Item>
            </Form>
        </PageLayer>
    );
});

export default IssueCoupon;